package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.StringUtils;
import com.example.demo.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.common.Result;
import com.example.demo.service.UserService;
import org.springframework.validation.annotation.Validated;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public Result<?> createUser(@Validated @RequestBody UserDTO userDTO) {
        // 这里应该调用 Service 层处理业务逻辑
        return Result.success("用户创建成功");
    }

    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Long id) {
        // 这里应该调用 Service 层查询用户
        return Result.success(new User());
    }

    @PutMapping("/{id}")
    public Result<?> updateUser(@PathVariable Long id, @Validated @RequestBody UserDTO userDTO) {
        // 这里应该调用 Service 层更新用户
        return Result.success("用户更新成功");
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteUser(@PathVariable Long id) {
        // 这里应该调用 Service 层删除用户
        return Result.success("用户删除成功");
    }

    @GetMapping
    public Result<Page<User>> getUserList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String email,
            @RequestParam(required = false) String phone) {
        
        // 构建查询条件
        Page<User> page = new Page<>(current, size);
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.hasLength(username)) {
            queryWrapper.like(User::getUsername, username);
        }
        if (StringUtils.hasLength(email)) {
            queryWrapper.like(User::getEmail, email);
        }
        if (StringUtils.hasLength(phone)) {
            queryWrapper.like(User::getPhone, phone);
        }
        
        // 按创建时间倒序
        queryWrapper.orderByDesc(User::getCreateTime);
        
        // 执行查询
        Page<User> userPage = userService.page(page, queryWrapper);
        return Result.success(userPage);
    }
} 